package com.example.dc.Controller;

import com.example.dc.Service.UserService;
import com.example.dc.domain.User;
import com.example.dc.utils.JWTUtils;
import com.example.dc.utils.MailUtils;
import com.example.dc.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private MailUtils mailUtils;
    @Autowired
    private UserService userService;

    /**
     * 返回一个验证码
     *
     * @return
     */
    @GetMapping("/getcode")
    public Result getCodeByEmail(String account, Character type) {
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) code += random.nextInt(10);
        // 存储验证记录
        userService.requestCode(account, code, type);
//            type='1' => 邮箱验证
        if (type == '1') {
            String subject = "账号登录";
            String message = "【心语悦年】您的验证码为：" + code + ",5分钟内有效。请勿泄漏";
//            String subject = "堂堂正正见老师";
//            String message = "篆刻离别烟雨江南————2012年3月12日";

            mailUtils.sendEmail(account, subject, message);

        }
//        type='0' =>手机号验证
        else if (type == '0') {

        }
        return Result.success(code);
    }
    public String test() {
        return "Hello World!";
    }
    @PostMapping("/register")
    public Result register(@RequestBody Map<String, Object> map) {
        String phone = (String) map.get("phone");
        String password = (String) map.get("password");

        // ✅ 兼容前端传字符串 "1" 或 "0"
        Object typeObj = map.get("type");
        Character type = null;
        if (typeObj instanceof String) {
            String typeStr = (String) typeObj;
            if (!typeStr.isEmpty()) {
                type = typeStr.charAt(0); // 取第一个字符
            }
        } else if (typeObj instanceof Character) {
            type = (Character) typeObj;
        }

        if (type == null) {
            return Result.error("type 参数无效");
        }

        if (userService.findUser(phone) > 0) return Result.error();
        System.out.println("YES!");
        userService.register(phone, password, type);
        System.out.println("YTT");
        return Result.success();
    }

    //用户登录
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        System.out.println(map.toString());
        String account = (String) map.get("account");
        String password = (String) map.get("password");
        String ip = (String) map.get("ip");
        String code = (String) map.get("code");
        Integer type = (Integer) map.get("type");
        System.out.println("type:" + type);
        System.out.println("ip:"+ip);
        //token验证成功，直接放行
        if (type == 2) {
            try {
                //获取请求路径的令牌
                String token=request.getHeader("Authorization");
                System.out.println("token:"+token);
                jwtUtils.parseToken(token);

                return Result.success();
            } catch (Exception err) {
                return Result.error("NOT_LOGIN");
            }
        }
        //验证码登录
        else if (type == 1) {
            // 1.判断登录方式
            Character loginType = isValidPhoneNumber(account) ? '1' : '0';//0:邮箱，1：手机号
            // 2.先验证验证码是否正确
            Character isRight = userService.codeIsRight(account, code) ? '1' : '0';// 1：成功，0：失败
            // 3.插入登录记录
            userService.insertLoginHistory(account, code,ip, loginType, isRight);
            //验证码错误
            if (isRight != '1') return Result.error("验证码错误!");
            // 4.是否是新用户
            User user = userService.getUserInfoByAccount(account);
            //是新用户
            if (user == null) {
                Integer userId=userService.register(account, "", loginType);
                //创建新用户对象
                user=new User();
                user.setId(userId);
                if (loginType == '0') {
                    user.setEmail(account);
                } else if (loginType == '1') {
                    user.setPhone(account);
                }
                user.setNickname("默认_用户");
            }

            // 5.生成JWT令牌
            String token = jwtUtils.setToken(account);
            Map<String, Object> result = new HashMap<>();
            result.put("user", user);
            result.put("token", token);
            return Result.success(result);//密码登录成功
        }
        //秘密登录
        else if(type==3){
            // 查询密码是否正确
            List<User> userObj = userService.findPassword(account);
            System.out.println("YES");
            String passwordInDb = userObj.get(0).getPassword();
            Integer userInfoId =  userObj.get(0).getId();
            System.out.println("userInfoId:" + userInfoId);
            if (passwordInDb == null || !passwordInDb.equals(password)) {
                userService.insertLoginHistory(account,password, ip, '3', '0');
                return Result.error("登录失败");//密码错误或用户不存在
            }
            // 密码正确，登录成功
            else {
                //生成JWT令牌
                String token = jwtUtils.setToken(account);
                //查询用户的信息
                User user = userService.getUserInfo(userInfoId);
                System.out.println(user);
                Map<String, Object> result = new HashMap<>();
                result.put("user", user);
                result.put("token", token);
                userService.insertLoginHistory(account,password, ip, '3', '1');
                return Result.success(result);//密码登录成功
            }
        }
        else{
            return Result.error();
        }
    }

    @GetMapping("/isFirst")
    public Result isFirst(Integer userId) {
        Boolean isFirst = userService.isFirst(userId);
        return Result.success(isFirst);
    }

    @GetMapping("/update/register")
    public Result updateRegistTime(Integer userId) {
        userService.updateRegistTime(userId);
        return Result.success();
    }

    @PostMapping("/edit/info")
    public Result editUserInfo(@RequestBody User user) {
        userService.editUser(user);
        return Result.success();
    }

    //        手机号验证
    public boolean isValidPhoneNumber(String phoneNumber) {
        if ((phoneNumber != null) && (!phoneNumber.isEmpty())) {
            return Pattern.matches("^1[3-9]\\d{9}$", phoneNumber);
        }
        return false;
    }

}
